Groovy (循环,Break语句,Continue语句,if语句,If/Else语句,嵌套If语句,Switch语句)

您所在的位置:网站首页 groovy each continue Groovy (循环,Break语句,Continue语句,if语句,If/Else语句,嵌套If语句,Switch语句)

Groovy (循环,Break语句,Continue语句,if语句,If/Else语句,嵌套If语句,Switch语句)

2024-07-10 04:56| 来源: 网络整理| 查看: 265

循环 -- while package com.klvchen.test1 class CycleTest { static void main(String[] args) { int count = 0; while(count < 5) { println(count); count++; } } }

运行结果:

循环 -- for package com.klvchen.test1 class CycleTest { static void main(String[] args) { for(int i = 0; i< 5; i++) { println(i); } } }

运行结果:

循环 -- for-in package com.klvchen.test1 class CycleTest { static void main(String[] args) { int[] array = [0, 1, 2, 3]; for(int i in array) { println(i); } } }

运行结果:

Break语句

break 语句用于更改loop和switch语句内的控制流。我们已经看到break语句与switch语句结合使用。break语句也可以与while和for语句一起使用。使用这些循环结构中的任何一个执行 break 语句会立即终止最内层的循环。

package com.klvchen.test1 class CycleTest { static void main(String[] args) { int[] array = [0, 1, 2, 3]; for(int i in array) { println(i); if(i == 2) break; } } } 运行结果:

Continue语句

continue 的使用局限于while和for循环。当执行continue语句时,控制立即传递到最近的封闭循环的测试条件,以确定循环是否应该继续。对于该特定循环迭代,循环体中的所有后续语句都将被忽略。

package com.klvchen.test1 class CycleTest { static void main(String[] args) { int[] array = [0, 1, 2, 3]; for(int i in array) { if(i == 2) continue; println(i); } } } 运行结果:

if语句 package com.klvchen.test1 class CycleTest { static void main(String[] args) { int a = 2; if(a5) { println("The value is greater than 5 and less than 100"); } else { println("The value is less than 5"); } } } }

运行结果:

Switch语句 package com.klvchen.test1 class CycleTest { static void main(String[] args) { int a = 2; switch(a) { case 1: println("The value of a is One"); break; case 2: println("The value of a is Two"); break; case 3: println("The value of a is Three"); break; case 4: println("The value of a is Four"); break; default: println("The value is unknown"); break; } } }

运行结果:

嵌套Switch语句 package com.klvchen.test1 class CycleTest { static void main(String[] args) { int i = 0; int j = 1; switch(i) { case 0: switch(j) { case 0: println("i is 0, j is 0"); break; case 1: println("i is 0, j is 1"); break; } break; default: println("No matching case found!!"); } } }

运行结果:



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3